let cow = document.getElementById('cow')
let cowX = cow.offsetLeft
let cowY = cow.offsetTop
let flag = true
let timeJg = true
let clientWidth = document.body.clientWidth
let clientHeight = document.body.clientHeight
let cowCall = document.getElementById('audio')
let btn = document.getElementById('btn')

function play () {
  let state = cowCall.paused
  if (state) {
    cowCall.play()
    cowCall.volume = 1
    btn.style.backgroundImage = 'url(./play.png)'
  } else {
    cowCall.pause()
    cowCall.volume = 0
    btn.style.backgroundImage = 'url(./puase.png)'
  }
}

// 获取dom到四个角的最长边
function getMaxLength () {
  let rb = Math.sqrt(((clientWidth - cowX) * (clientWidth - cowX)) + ((clientHeight - cowY) * (clientHeight - cowY)))
  let rt = Math.sqrt(((clientWidth - cowX) * (clientWidth - cowX)) + (cowY * cowY))
  let lb = Math.sqrt((cowX * cowX) + ((clientHeight - cowY) * (clientHeight - cowY)))
  let lt = Math.sqrt((cowX * cowX) + (cowY * cowY))
  let list = [rb, rt, lb, lt].sort((a, b) => { return b - a })
  return list[0]
}

// 调整鼠标移动时音频播放速度
function playAudio (x, y) {
  if (timeJg) {
    timeJg = false
    let maxLength = getMaxLength()
    let dis = Math.sqrt((x * x) + (y * y))
    let speed = (((maxLength - dis) / maxLength) * 15.5) + 0.5
    setTimeout(() => {
      cowCall.playbackRate = speed
      timeJg = true
    }, 100);
  }
}

// 找到dom之后重置dom位置
function resetCow () {
  cowCall.pause()
  if (flag) {
    flag = false
    cow.style.opacity = 1
    setTimeout(() => {
      let maxX = clientWidth - 300
      let maxY = clientHeight - 300
      let newX = Math.floor(Math.random() * maxX) + 150
      let newY = Math.floor(Math.random() * maxY) + 150
      setTimeout(() => {
        cow.style.left = newX + 'px'
        cow.style.top = newY + 'px'
      }, 500)
      cowX = newX
      cowY = newY
      flag = true
      cowCall.play()
      cow.style.opacity = 0
    }, 3000)
  }
}

// 初始化
function init () {
  document.body.onmousemove = ({ clientX, clientY }) => {
    let oldX = cow.offsetLeft
    let oldY = cow.offsetTop
    let x = Math.abs(clientX - oldX)
    let y = Math.abs(clientY - oldY)
    if (x < 100 && y < 100) {
      resetCow()
    }
    playAudio(x, y)
  }
}

init();